package com.hmall.common.config;

import com.hmall.common.interceptor.MQConsumerInterceptor;
import com.hmall.common.utils.UserContext;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ配置类，用于自动处理用户信息在MQ中的传递
 */
@Configuration
@ConditionalOnClass(RabbitListener.class)
public class RabbitConfig {

    @Autowired
    private MQConsumerInterceptor mqConsumerInterceptor;

    /**
     * 消息发送前处理器，自动将当前用户信息添加到消息头中
     *
     * @return MessagePostProcessor
     */
    @Bean
    public MessagePostProcessor userContextPostProcessor() {
        return message -> {
            Long userId = UserContext.getUser();
            if (userId != null) {
                message.getMessageProperties().setHeader("user-info", userId.toString());
            }
            return message;
        };
    }
}